<template>
  <!-- pages/address_edit/address_edit.wxml -->
  <view class="address-edit">
    <!-- #ifndef  H5 -->
    <u-sticky offset-top="0" h5-nav-height="0" bg-color="transparent">
      <u-navbar
          :is-back="true"
          :title-bold="true"
          :is-fixed="false"
          :title="navTitle"
          title-color="#000000"
          :border-bottom="false"
          back-icon-name="arrow-leftward"
          back-icon-color="#000000"
          :background="{ background: 'rgba(256,256, 256,0)' }"
      ></u-navbar>
    </u-sticky>
    <!-- #endif -->
    <view class="content-wrapper">
      <form @submit="formSubmit" report-submit="true" class="form-container">
        <view class="form bg-white">
          <view class="form-item row">
            <view class="label">联系人:</view>
            <input
                class="ml10"
                v-model="addressObj.contact"
                name="contact"
                type="text"
                placeholder="请输入姓名"
            />
          </view>
          <view class="form-item row">
            <view class="label">手机号:</view>
            <input
                class="ml10"
                name="telephone"
                v-model="addressObj.telephone"
                type="number"
                placeholder="请输入手机号"
            />
          </view>
          <view @click="showRegion = true">
            <view class="form-item row">
              <view class="label">所在地区:</view>
              <input
                  class="ml10"
                  name="region"
                  v-model="region"
                  disabled
                  type="text"
                  placeholder="请选择省、市、区"
              />
              <image class="icon-sm ml10" src="/static/images/arrow_right.png"/>
            </view>
          </view>
          <view>
            <u-field

                v-model="addressObj.address"
                type="textarea"
                label="详细地址:"
                placeholder="请填写小区、街道、门牌号等信息"
                :field-style="{ flex: 1,  height: '160rpx' }"
                :border-bottom="false"
            />
          </view>
        </view>
        <view class="mt10 mb10 bg-white check-wrap  row-between">
          <label for="checkbox">
            <text>设为默认地址</text>
          </label>
          <u-switch v-model="addressObj.is_default" size="38" active-color="#2d6af4"></u-switch>
        </view>
        <!-- 将按钮放在底部 -->
        <view class="footer-btn">
          <button class="my-btn bg-primary white br60" form-type="submit">保存</button>
        </view>
      </form>
    </view>
    <u-select
        v-model="showRegion"
        mode="mutil-column-auto"
        @confirm="regionChange"
        :list="lists"
    ></u-select>
  </view>
</template>

<script>

import {editAddress, getOneAddress, hasRegionCode, addAddress} from '@/api/user'
import area from '@/utils/area'

export default {
  data() {
    return {
      navTitle: '新增地址',
      addressObj: {
        contact: '',
        telephone: '',
        province: '',
        city: '',
        district: '',
        address: '',
        is_default: 0,

      },
      region: '',
      addressId: '',
      defaultRegion: ['广东省', '广州市', '番禺区'],
      defaultRegionCode: '440113',
      showRegion: false,
      lists: []
    }
  },
  props: {},

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.addressId = parseInt(options.id)
    if (options.id) {
      this.navTitle = '修改地址';
      this.getOneAddressFun()
    } else {
      this.navTitle = '新增地址';
      // this.getWxAddressFun()
    }
    this.$nextTick(() => {
      this.lists = area
    })
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    uni.removeStorageSync('wxAddress')
  },

  /**
   * 用户点击右上角分享
   */
  // onShareAppMessage: function () {},
  methods: {
    formSubmit(e) {
      let {value} = e.detail
      let {
        addressObj: {province_id, city_id, district_id, is_default, address},
        addressId
      } = this
      value.address = address
      if (!value.contact)
        return this.$toast({
          title: '请填写收货人姓名'
        })
      if (!value.telephone)
        return this.$toast({
          title: '请填写手机号码'
        })
      if (!value.region)
        return this.$toast({
          title: '请选择省、市、区'
        })
      if (!value.address)
        return this.$toast({
          title: '请填写小区、街道、门牌号等信息'
        })
      value.province_id = parseInt(province_id)
      value.city_id = parseInt(city_id)
      value.district_id = parseInt(district_id)
      value.is_default = is_default
      value.id = addressId
      delete value.region

      if (addressId) {
        editAddress(value)
            .then((res) => {
              if (res.code == 1) {
                this.$toast(
                    {
                      title: res.msg
                    },
                    {
                      tab: 3,
                      url: 1
                    }
                )
              }
            })
            .catch((err) => {
              return this.$toast({
                title: err
              })
            })
      } else {
        addAddress(value)
            .then((res) => {
              if (res.code == 1) {
                this.$toast(
                    {
                      title: res.msg
                    },
                    {
                      tab: 3,
                      url: 1
                    }
                )
              }
            })
            .catch((err) => {
              return this.$toast({
                title: err
              })
            })
      }
    },
    regionChange(region) {
      this.addressObj.province_id = region[0].value
      this.addressObj.city_id = region[1].value
      this.addressObj.district_id = region[2].value
      this.region = region[0].label + ' ' + region[1].label + ' ' + region[2].label
    },

    ChangeIsDefault: function (e) {
      if (this.addressObj.is_default == 0) {
        this.addressObj.is_default = 1
      } else {
        this.addressObj.is_default = 0
      }
    },

    textareaChange: function (e) {
      this.addressObj.address = e.detail.value
    },

    getOneAddressFun() {
      getOneAddress(this.addressId).then((res) => {
        if (res.code == 1) {
          let {city, province, district} = res.data
          this.addressObj = res.data
          this.region = `${province} ${city} ${district}`
        }
      })
    },

    getWxAddressFun() {
      let wxAddress = uni.getStorageSync('wxAddress')
      if (!wxAddress) return
      wxAddress = JSON.parse(wxAddress)
      let {
        userName: contact,
        telNumber: telephone,
        provinceName: province,
        cityName: city,
        detailInfo: address
      } = wxAddress
      let district = wxAddress.countryName || wxAddress.countyName
      hasRegionCode({
        province,
        city,
        district
      }).then((res) => {
        if (res.code == 1) {
          if (res.data.province && res.data.city && res.data.district) {
            this.addressObj.province_id = res.data.province
            this.addressObj.city_id = res.data.city
            this.addressObj.district_id = res.data.district
            this.region = `${province} ${city} ${district}`
          }
          this.addressObj.contact = contact
          this.addressObj.telephone = telephone
          this.addressObj.address = address
        }
      })
    }
  }
}
</script>
<style lang="scss">
/* pages/address_edit/address_edit.wxss */
page {
  background-image: url("../../static/images/my_bg.jpg");
  background-size: 100%;
  background-repeat: no-repeat;

  .address-edit {
    padding-top: 10rpx;
    display: flex;
    flex-direction: column;
    min-height: 100vh;

    .content-wrapper {
      flex: 1;
      display: flex;
      flex-direction: column;

      .form-container {
        flex: 1;
      }

      .footer-btn {
        margin-top: auto;
        background-color: #fff;
      }
    }

    .form {
      flex: 1;
      border-radius: 16rpx;
      padding: 20rpx;
      margin: 20rpx;
      color: #414040;

      .form-item {
        margin: 0 20rpx;
        height: 80rpx;

        &:not(:nth-of-type(3)) {
          //border-bottom: $-solid-border;
          border-bottom: #f0f1f5;
        }

        .label {
          width: 150rpx;
        }

        input {
          height: 100%;
          flex: 1;
        }
      }
    }


    .check-wrap {
      padding: 35rpx 30rpx;
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin: 0 20rpx;
      border-radius: 16rpx;
    }
    .footer-btn{
      position: fixed;
      left: 0;
      right: 0;
      bottom: 0;
      height: 118rpx;
      padding: 0 30rpx;
      box-sizing: content-box;
      padding-bottom: env(safe-area-inset-bottom);
      background-color: #fff;
    }
    .my-btn {
      width: 50%;
      margin: 20rpx auto;
      //flex: 1;
      height: 80rpx;
      background-image: linear-gradient(to bottom, #6aa0ff, #2d6af4);
    }
  }

  van-field view {
    height: 100%;
  }

  van-field textarea {
    height: 100% !important;
    padding-top: 10rpx !important;
  }

  .van-cell {
    padding: 20rpx !important;
  }

  .van-field__body--textarea,
  .van-field__input {
    margin-left: 15rpx;
  }
}

.bg-primary {
  background-color: #2d6af4;
}
</style>
